{% extends "admin/admin_base.html" %}

{% block title %}卡密管理{% endblock %}
{% block breadcrumb %}卡密管理{% endblock %}

{% block head %}
{{ super() }}
<style>
    /* 统计卡片 */
    .stats-container {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
        margin-bottom: 1.5rem;
    }

    .stat-card {
        background-color: white;
        border-radius: 0.75rem;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        padding: 1.5rem;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }

    .stat-card-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 1rem;
    }

    .stat-card-title {
        color: #86909C;
        font-size: 0.875rem;
        font-weight: 500;
    }

    .stat-card-icon {
        width: 40px;
        height: 40px;
        border-radius: 0.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
    }

    .stat-card-icon.primary {
        background-color: rgba(22, 93, 255, 0.1);
        color: #165DFF; /* 主色 */
    }

    .stat-card-icon.success {
        background-color: rgba(82, 196, 26, 0.1);
        color: #52C41A; /* 成功色 */
    }

    .stat-card-icon.warning {
        background-color: rgba(250, 173, 20, 0.1);
        color: #FAAD14; /* 警告色 */
    }

    .stat-card-icon.danger {
        background-color: rgba(255, 77, 79, 0.1);
        color: #FF4D4F; /* 危险色 */
    }

    .stat-card-value {
        font-size: 1.75rem;
        font-weight: 600;
        margin-bottom: 0.5rem;
        color: #1D2129;
    }

    /* 徽章样式 */
    .badge {
        padding: 0.25rem 0.5rem;
        border-radius: 999px;
        font-size: 0.75rem;
        font-weight: 500;
    }

    .badge-success {
        background-color: rgba(82, 196, 26, 0.1);
        color: #52C41A;
    }

    .badge-danger {
        background-color: rgba(255, 77, 79, 0.1);
        color: #FF4D4F;
    }

    .badge-warning {
        background-color: rgba(250, 173, 20, 0.1);
        color: #FAAD14;
    }

    .badge-primary {
        background-color: rgba(22, 93, 255, 0.1);
        color: #165DFF;
    }

    /* 卡密类型徽章 */
    .badge-month {
        background-color: #FFF9C4;
        color: #D4AF37;
        border: 1px solid #FFECB3;
    }

    .badge-season {
        background-color: #E3F2FD;
        color: #1976D2;
        border: 1px solid #BBDEFB;
    }

    .badge-year {
        background: linear-gradient(135deg, #7B1FA2 0%, #4A148C 100%);
        color: #FFFFFF;
        box-shadow: 0 2px 4px rgba(123, 31, 162, 0.15);
    }

    .badge-free {
        background-color: #F5F5F5;
        color: #616161;
        border: 1px solid #EEEEEE;
    }

    /* 操作按钮 */
    .action-btn {
        padding: 0.25rem 0.5rem;
        border-radius: 4px;
        transition: all 0.2s ease;
    }

    /* 模态框样式（适配现有风格） */
    .form-modal {
        display: none; /* 默认隐藏 */
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
        align-items: center;
        justify-content: center;
    }

    .modal-content {
        background-color: #fff;
        border-radius: 8px;
        width: 100%;
        max-width: 500px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    }

    .modal-header {
        padding: 16px 24px;
        border-bottom: 1px solid #E5E6EB;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .modal-title {
        font-size: 16px;
        font-weight: 600;
        color: #1D2129;
        margin: 0;
    }

    .modal-close {
        background: none;
        border: none;
        font-size: 20px;
        color: #86909C;
        cursor: pointer;
        padding: 0;
    }

    .modal-body {
        padding: 24px;
    }

    .modal-footer {
        padding: 16px 24px;
        border-top: 1px solid #E5E6EB;
        display: flex;
        justify-content: flex-end;
        gap: 12px;
    }

    /* 提示弹窗 */
    .toast {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        padding: 16px;
        border-radius: 4px;
        color: #fff;
        font-size: 14px;
        opacity: 0;
        transition: opacity 0.3s ease;
    }

    .toast.success {
        background-color: #52C41A;
    }

    .toast.error {
        background-color: #FF4D4F;
    }

    .toast.show {
        opacity: 1;
    }
</style>
{% endblock %}

{% block content %}
<!-- 提示弹窗 -->
<div class="toast" id="toast"></div>

<!-- 统计卡片（绑定后端传来的统计数据） -->
<div class="stats-container">
    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">总卡密</div>
            <div class="stat-card-icon primary">
                <i class="fas fa-key"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ total_kami }}</div>
        <div class="text-muted text-sm">已使用: {{ used_kami }} 张 / 未使用: {{ unused_kami }} 张</div>
    </div>

    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">黄金月卡</div>
            <div class="stat-card-icon success">
                <i class="fas fa-calendar-month"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ month_count }}</div>
        <div class="text-muted text-sm">有效期: 30天</div>
    </div>

    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">铂金季卡</div>
            <div class="stat-card-icon warning">
                <i class="fas fa-calendar-week"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ season_count }}</div>
        <div class="text-muted text-sm">有效期: 90天</div>
    </div>

    <div class="stat-card">
        <div class="stat-card-header">
            <div class="stat-card-title">至尊年卡</div>
            <div class="stat-card-icon danger">
                <i class="fas fa-calendar-year"></i>
            </div>
        </div>
        <div class="stat-card-value">{{ year_count }}</div>
        <div class="text-muted text-sm">有效期: 365天</div>
    </div>
</div>

<!-- 卡密表格（修正Bootstrap样式） -->
<div class="data-table mb-4">
    <div class="table-header">
        <div class="table-title">卡密列表</div>
        <div class="table-actions">
            <!-- 搜索表单 -->
            <form id="searchForm" class="input-group" style="width: 300px; margin-right: 12px;" method="get">
                <input type="hidden" name="page" value="{{ page or 1 }}">
                <input type="text" name="search" class="form-control" placeholder="搜索卡密/用户名..."
                       value="{{ search or '' }}">
                <button class="btn btn-primary" type="submit">
                    <i class="fas fa-search"></i>
                </button>
            </form>
            <!-- 添加卡密按钮 -->
            <button class="btn btn-primary" id="addKamiBtn">
                <i class="fas fa-plus"></i> 生成卡密
            </button>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-hover table-striped"> <!-- 补全Bootstrap表格类 -->
            <thead class="table-light">
            <tr>
                <th>卡密ID</th>
                <th>卡密Key</th>
                <th>卡密类型</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>激活用户</th>
                <th>激活时间</th>
                <th>备注</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% if kamis %}
                {% for kami in kamis %}
                <tr>
                    <td>{{ kami.id }}</td>
                    <td>{{ kami.code }}</td>
                    <td>
                        {% if kami.vip_type.value == 'month' %}
                        <span class="badge badge-month">黄金月卡</span>
                        {% elif kami.vip_type.value == 'season' %}
                        <span class="badge badge-season">铂金季卡</span>
                        {% elif kami.vip_type.value == 'year' %}
                        <span class="badge badge-year">至尊年卡</span>
                        {% else %}
                        <span class="badge badge-free">未知类型</span>
                        {% endif %}
                    </td>
                    <td>
                        {% if kami.is_used == 1 %}
                        <span class="badge badge-success">已使用</span>
                        {% else %}
                        <span class="badge badge-danger">未使用</span>
                        {% endif %}
                    </td>
                    <td>{{ kami.created_at.strftime('%Y-%m-%d %H:%M') if kami.created_at else '--' }}</td>
                    <td>{{ kami.user.username if kami.user and kami.user.username else '--' }}</td>
                    <td>{{ kami.used_at.strftime('%Y-%m-%d %H:%M') if kami.used_at else '--' }}</td>
                    <td>{{ kami.remark if kami.remark else '--' }}</td>
                    <td>
                        <!-- 查看按钮（暂用提示代替） -->
                        <button class="action-btn btn btn-sm btn-info" title="查看详情"
                                onclick="showToast('提示', '卡密详情：{{ kami.code }}', 'success')">
                            <i class="fas fa-eye"></i>
                        </button>
                        <!-- 禁用/启用按钮 -->
                        <button class="action-btn btn btn-sm {% if kami.status == 1 %}btn-danger{% else %}btn-success{% endif %}"
                                title="{% if kami.status == 1 %}禁用{% else %}启用{% endif %}"
                                data-id="{{ kami.id }}" data-status="{{ kami.status }}">
                            <i class="fas {% if kami.status == 1 %}fa-ban{% else %}fa-check{% endif %}"></i>
                        </button>
                    </td>
                </tr>
                {% endfor %}
            {% else %}
                <tr>
                    <td colspan="9" class="text-center py-4">
                        <i class="fas fa-key text-muted" style="font-size: 1.5rem;"></i>
                        <p class="mt-2 text-muted">暂无卡密数据</p>
                    </td>
                </tr>
            {% endif %}
            </tbody>
        </table>
    </div>

    <!-- 分页（优化逻辑，避免页数过多） -->
    <div class="pagination-container d-flex justify-content-between align-items-center mt-3 px-3">
    <div class="pagination-info">显示 {{ kamis|length }} 条，共 {{ total_kami }} 条</div>
    <div class="pagination">
        <!-- 上一页 -->
        <a href="?page={{ page-1 if page > 1 else 1 }}{% if search %}&search={{ search }}{% endif %}"
           class="btn btn-outline-primary {% if page == 1 %}disabled{% endif %}">
            <i class="fas fa-chevron-left"></i>
        </a>

        <!-- 分页按钮（修复 max/min 问题） -->
        {% if total_pages > 0 %}
            {% set start_page = (page - 2) if (page - 2) >= 1 else 1 %}
            {% set end_page = (page + 2) if (page + 2) <= total_pages else total_pages %}
            {% for p in range(start_page, end_page + 1) %}
                <a href="?page={{ p }}{% if search %}&search={{ search }}{% endif %}"
                   class="btn btn-outline-primary {% if p == page %}active{% endif %}">{{ p }}</a>
            {% endfor %}
        {% endif %}

        <!-- 下一页 -->
        <a href="?page={{ page+1 if page < total_pages else total_pages }}{% if search %}&search={{ search }}{% endif %}"
           class="btn btn-outline-primary {% if page == total_pages %}disabled{% endif %}">
            <i class="fas fa-chevron-right"></i>
        </a>
    </div>
</div>
</div>

<!-- 添加卡密模态框 -->
<div class="form-modal" id="addKamiModal">
    <div class="modal-content">
        <form id="addKamiForm">
            <div class="modal-header">
                <h3 class="modal-title">生成卡密</h3>
                <button class="modal-close" type="button">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group mb-3">
                    <label class="form-label">卡密类型 <span class="text-danger">*</span></label>
                    <select name="vip_type" class="form-select" required>
                        <option value="month">黄金月卡（30天）</option>
                        <option value="season">铂金季卡（90天）</option>
                        <option value="year">至尊年卡（365天）</option>
                    </select>
                </div>
                <div class="form-group mb-3">
                    <label class="form-label">生成数量 <span class="text-danger">*</span></label>
                    <input type="number" name="count" class="form-control" value="1" min="1" max="100" required>
                    <div class="form-text">单次最多生成100张卡密</div>
                </div>
                <div class="form-group mb-3">
                    <label class="form-label">备注</label>
                    <input type="text" name="remark" class="form-control" placeholder="例如：2024年10月活动卡密">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline-secondary" type="button" id="cancelAddKami">取消</button>
                <button class="btn btn-primary" type="submit">生成卡密</button>
            </div>
        </form>
    </div>
</div>



{% endblock %}

{% block scripts %}
{{ super() }}
<script>
// 全局变量（从模板获取）
const currentPage = {{ page or 1 }};
const totalPages = {{ total_pages or 1 }};

// 1. 模态框控制
// 页面加载完成后再绑定事件（确保DOM已渲染）
document.addEventListener('DOMContentLoaded', function() {
    // 1. 打印日志，验证JS是否执行（用于调试）
    console.log("DOM加载完成，开始绑定卡密按钮事件");

    // 2. 精准获取DOM元素（避免选择器错误）
    const addBtn = document.getElementById('addKamiBtn');
    const addModal = document.getElementById('addKamiModal');
    const closeBtn = addModal.querySelector('.modal-close'); // 从模态框内部找关闭按钮
    const cancelBtn = document.getElementById('cancelAddKami');
    const addForm = document.getElementById('addKamiForm');

    // 3. 验证元素是否找到（关键：若打印为null，说明ID拼写错误）
    console.log("生成卡密按钮元素：", addBtn);
    console.log("模态框元素：", addModal);
    console.log("关闭按钮元素：", closeBtn);
    console.log("取消按钮元素：", cancelBtn);

    // 4. 显示模态框函数（单独提取，避免重复代码）
    function showModal() {
        console.log("触发显示模态框");
        addModal.style.display = 'flex'; // 确保是flex，不是block
        // 可选：显示时聚焦到第一个输入框，提升体验
        addForm.querySelector('select[name="vip_type"]').focus();
    }

    // 5. 隐藏模态框函数
    function hideModal() {
        addModal.style.display = 'none';
        addForm.reset(); // 重置表单
    }

    // 6. 绑定“生成卡密”按钮点击事件（核心修复）
    if (addBtn) {
        addBtn.addEventListener('click', function(e) {
            e.stopPropagation(); // 阻止事件冒泡（避免被父元素拦截）
            showModal();
        });
    } else {
        console.error("ERROR：未找到“生成卡密”按钮，请检查ID是否为addKamiBtn");
    }

    // 7. 绑定关闭按钮事件
    if (closeBtn) {
        closeBtn.addEventListener('click', hideModal);
    }

    // 8. 绑定取消按钮事件
    if (cancelBtn) {
        cancelBtn.addEventListener('click', hideModal);
    }

    // 9. 点击模态框外部关闭（确保事件绑定到正确元素）
    if (addModal) {
        addModal.addEventListener('click', function(e) {
            // 只有点击模态框背景（不是内部内容）才关闭
            if (e.target === addModal) {
                hideModal();
            }
        });
    }

    // 2. 生成卡密表单提交
    addForm.addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(this);

        fetch('/admin/kami/generate', {
            method: 'POST',
            body: formData,
            credentials: 'include' // 携带登录状态
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showToast('成功', `已生成${data.count}张卡密`, 'success');
                hideModal();
                // 刷新页面，显示新卡密
                setTimeout(() => window.location.reload(), 1500);
            } else {
                showToast('错误', data.msg || '生成失败', 'error');
            }
        })
        .catch(err => {
            console.error('生成卡密失败:', err);
            showToast('错误', '网络异常，请重试', 'error');
        });
    });

    // 3. 卡密启用/禁用
    document.querySelectorAll('.action-btn[data-id]').forEach(btn => {
        btn.addEventListener('click', function() {
            const kamiId = this.getAttribute('data-id');
            const currentStatus = this.getAttribute('data-status');
            const newStatus = currentStatus == 1 ? 0 : 1; // 切换状态
            const statusText = newStatus == 1 ? '启用' : '禁用';

            if (!confirm(`确定要${statusText}这张卡密吗？`)) return;

            fetch(`/admin/kami/update_status`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ kami_id: kamiId, status: newStatus }),
                credentials: 'include'
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    showToast('成功', `卡密已${statusText}`, 'success');
                    // 局部更新按钮状态（无需刷新页面）
                    this.setAttribute('data-status', newStatus);
                    this.className = `action-btn btn btn-sm ${newStatus == 1 ? 'btn-danger' : 'btn-success'}`;
                    this.innerHTML = `<i class="fas ${newStatus == 1 ? 'fa-ban' : 'fa-check'}"></i>`;
                    this.title = statusText;
                } else {
                    showToast('错误', data.msg || '操作失败', 'error');
                }
            })
            .catch(err => {
                console.error('更新卡密状态失败:', err);
                showToast('错误', '网络异常，请重试', 'error');
            });
        });
    });
});

// 4. 提示弹窗函数
function showToast(title, msg, type) {
    const toast = document.getElementById('toast');
    toast.className = `toast ${type} show`;
    toast.innerHTML = `<strong>${title}!</strong> ${msg}`;
    setTimeout(() => toast.className = 'toast', 3000);
}
</script>
{% endblock %}